const { plugin } = require("../../../../common/utils")
const { calculRoute, calculP, randomCenter, findClosest, findFarthest, suitableTarget } = require("../../../../common/compute")
const { predefine } = require("../../../config/template")
const GameDetectProcessor = function() {
    this.coward = undefined,
    this.dungeons = [1,2,2,3,2,2,2,2],
    this.finish = false,
    this.goToNext = true,
    this.contTimes=0,
    this.level = 1,
    this.refresh = function(coward, black_diamond, objects) {
        if (black_diamond) {
            let t = suitableTarget(black_diamond)
            console.log("识别到黑钻:" + JSON.stringify({x: t.x - 140, y: t.y - 30, w: 150, h: 340}))
            coward.refresh({x: t.x - 140, y: t.y - 30, w: 150, h: 320})
        } else {
            coward.refresh(suitableTarget(objects) || {})
        }
        if (objects == undefined && black_diamond == null) {
            console.log("角色未识别到")
        } 
        return coward
    },
    this.adjust = function(coward) {
        if (!coward || !coward.bounds) {
            return
        }
        let w = Math.max(device.width, device.height)
        let h = Math.min(device.width, device.height)
        if (coward.bounds.x <= w / 2 && coward.bounds.y <= h / 2) {
            coward.move({angle: 45, distance: 100})
        }
        if (coward.bounds.x <= w / 2 && coward.bounds.y > h / 2) {
            coward.move({angle: 315, distance: 100})
        }
        if (coward.bounds.x > w / 2 && coward.bounds.y <= h / 2) {
            coward.move({angle: 135, distance: 100})
        }
        if (coward.bounds.x > w / 2 && coward.bounds.y > h / 2) {
            coward.move({angle: 225, distance: 100})
        }
    }
    this.cont = function(conts) {
        let cont = suitableTarget(conts)
        console.info("识别到继续：" + (!cont || !cont.x))
        if (!cont || !cont.x) {
            return false
        }
        this.contTimes = this.contTimes + 1
        let random = 5 - Math.random() * 10
        click(cont.x + random + cont.w / 2, cont.y + random + cont.h / 2)
        sleep(1000)
        let capture = captureScreen()
        let bitmap = capture.getBitmap()
        let target = plugin.match(bitmap, ["common/confirm"], [0.3, 0.7, 0.3, 0.7])
        console.info("识别到确认按钮:" + JSON.stringify(target))
        if (target == undefined) {
            return true
        }
        this.level = 1
        this.contTimes = -1
        click(target.x + random + target.w / 2, target.y + random + target.h / 2)
        return true
    }
    this.figth = function(level, monsters, coward) {
        console.info(JSON.stringify(monsters))
        if (!monsters || monsters.length == 0) {
            return false
        }
        // debuger.refresh()
        // debuger.addLine({x1:closest.p1.x,y1:closest.p1.y,x2:closest.p2.x,y2:closest.p2.y})
        if (this.goToNext) {
            this.level = this.level + 1
            console.info("清图之后第一次遇到怪物,释放大技能")
            // if (this.level == 8 && closest != undefined && !isNaN(closest.distance)) {
            //     closest.distance = closest.distance - 10
            // }
            if (this.level == 9) {
                this.level = 8
            }
            let pre = predefine["berserker"][this.level - 1]
            console.log("预定义动作:", JSON.stringify(pre))
            if (pre.bufs) {
                coward.fight(pre.bufs)
            }
            coward.move(pre, false)
            coward.fight(pre.skills)
            this.goToNext = false
        } else {
            let closest = findClosest(coward.bounds, monsters)
            coward.move(closest, true)
            coward.fightTemplate(this.level)
        }
        return true
    },
    this.pickup = function(rewards, guidancies, coward) {
        if (!rewards || rewards.length == 0) {
            return false
        }
        let guidance = undefined
        if (guidancies) {
            let direct = this.dungeons[this.level]
            console.info("当前移动方向:" + direct)
            guidance = findFarthest(coward.bounds, guidancies)
        }
        console.log("规划路径1:" + JSON.stringify(rewards))
        console.log("规划路径2:" + (guidance != undefined))
        let route = calculRoute(coward.bounds, rewards, guidance != undefined ? guidance.target : undefined)
        //let closest = findClosest(coward.bounds, rewards)
        //console.info("最近的奖励：" + JSON.stringify(closest))
        console.log("规划路径:" + JSON.stringify(route))
        coward.route(route)
        return true
        //{"angle":30,"distance":150,"skills":[7,2,1]}
        // debuger.refresh()
        // debuger.addLine({x1:closest.p1.x,y1:closest.p1.y,x2:closest.p2.x,y2:closest.p2.y})
    },
    this.repair = function( objects) {
        let repair = suitableTarget(objects["repair"])
        if (!repair) {
            return false
        }
        let random = 5 - Math.random() * 10
        click(repair.x + random + repair.w / 2, repair.y + random + repair.h / 2)
        sleep(2000)
        let capture = captureScreen()
        let bitmap = capture.getBitmap()
        let target = plugin.match(bitmap, ["dungeons/common/repair"], [0.3, 0.7, 0.5, 1])
        if (target != undefined) {
            click(target.x + random + target.w / 2, target.y + random + target.h / 2)
        }
        sleep(2000)
        click(10, 500 + random)
        return true
    }
    this.next = function(level, objects, coward) {
        let direct = this.dungeons[this.level]
        console.info("当前移动方向:" + direct)
        let guidance = undefined//this.dungeons.specialRoute(level)
        if (!guidance && objects && objects["guidance"]) {
            guidance = findFarthest(coward.bounds, objects["guidance"])//calculP(objects["guidance"], direct))
        }
        if (objects["door"] && guidance) {
            let door = findClosest(guidance.target, objects["door"])
            console.log("计算最近的门的距离：" + JSON.stringify(door))
            if (door.distance <= 300) {
                guidance = findClosest(coward.bounds, [door.target])//calculP([door.target], direct))
            }
        }
        if (!guidance) {
            return false
        }
        let route = []
        if (guidance.distance <= 300) {
            route.push({
                distance: 100,
                angle: (guidance.angle + 180) % 360
            })
            guidance.distance = guidance.distance + 120
            console.log("距离门过近重新回头调整距离")
        }
        route.push(guidance)
        console.log("过门路径:" + JSON.stringify(route))
        coward.route(route)
        return true
    },
    this.correction = function() {
        if (this.temp["corrected"]) {
            return
        }
        this.temp["level"] = this.dungeons.acquireLevel()
        this.temp["corrected"] = true
    },
    this.blackScreen = function(objects) {
        let blackScreen = objects["black-screen"]
        if (blackScreen == undefined) {
            return false
        }
        if (blackScreen.length > 0) {
            console.log("识别到黑屏--------------------")
            this.goToNext = true
        }
        return true
    },
    this.process = function(type, objects, runtime) {
        if (this.blackScreen(objects)) {
            return false
        }
        if (type == "black-screen-detect") {
            return false
        }
        //检测矫正房间号等信息，防止误判
        console.info("当前关卡:" + this.level)
        console.log("识别到结果:" + JSON.stringify(objects) + "," + this.contTimes)
        let coward = this.refresh(runtime.coward, objects["black_diamond"], objects["coward"])
        if (!objects["guidance"]) {
            if(this.figth(this.level, objects["monster"], coward)) {
                return false
            }
        }
        // //无怪物拾取掉落奖励
        if (this.pickup(objects["reward"], objects["guidance"], coward)) {
            return false
        }
        //自动修理装备
        this.repair(objects)
        if (this.cont(objects["next"])) {
            return false
        }
        if (this.next(this.level, objects, coward)) {
            return false
        }
        coward.move({angle: Math.floor(Math.random() * 360) + 1, distance: 100})
        return false
    },
    this.process
}

exports.gameDetectProcessor = new GameDetectProcessor() 